<?php
namespace app\controller;

use think\Request;
use think\facade\Db;
use app\model\Bazaar;
use app\model\Expand;
use app\model\Campaign;
use app\model\Customer;
use app\model\Principal;

class SemCreative extends Common
{

	/**
	 * 请求类型
	 *
	 * @return
	 */
	public function method(Request $request)
	{
		if($this->hasPermission($request->sessInfo, 'semcreative:read')) {
			return ['code'=> 403, 'msg'=> '你没有权限执行此操作!'];;
		}

		$where = [];
		$search = [];
		$limit = $request->param('limit/d', 20);
		$sort = $request->param('sort', 'id', 'trim');
		$order = $request->param('order', 'desc', 'trim');
		if( in_array($sort, ['impression', 'clicks', 'cost', 'cash', 'rebate', 'copynumber', 'cpc', 'ctr', 'copycost']) ) {
			$sort = 's.'.$sort;
		} else {
			$sort = 'c.'.$sort;
		}

		array_push( $search, " s.companyId = {$request->sessInfo['companyId']} ");
		array_push( $where, ['c.companyId', '=', $request->sessInfo['companyId'] ] );
		array_push( $where, ['c.userType', '=', 1 ] );

		$bazaarId = $request->param('bazaarId', '', 'trim');
		if($bazaarId) {
			array_push( $where, ['c.bazaarId', '=',  $bazaarId ] );
		}

		$userId = $request->param('userId', '', 'trim');
		if($userId) {
			array_push( $where, ['c.userId', '=',  $userId ] );
		}
		
		$customerid = $request->param('customerid', '', 'trim');
		if($customerid) {
			array_push( $where, ['c.customerid', '=',  $customerid ] );
		}

		$contact = $request->param('contact', '', 'trim');
		if($contact) {
			array_push( $where, ['c.contact', '=',  $contact ] );
		}

		$campaignId = $request->param('campaignId', '', 'trim');
		if($campaignId) {
			array_push( $where, ['c.campaignId', 'in',  $campaignId ] );
		}

		$status = $request->param('status', '', 'trim');
		if($status) {
			array_push( $where, ['c.status', '=',  $status ] );
		}

		$createTimeStart = $request->param('createTimeStart', '', 'trim');
		$createTimeEnd = $request->param('createTimeEnd', '', 'trim');
		if( $createTimeStart && $createTimeEnd ) {
			$time = cloud_datetime_format( $createTimeStart, $createTimeEnd, true);
			array_push( $search, " `s`.`datatime` BETWEEN {$time[0]} AND {$time[1]} ");
		} else {
			$time = cloud_datetime_format( date('Y-m-d 00:00:00'), date('Y-m-d 00:00:00', strtotime("+1 day")), true);
			array_push( $search, " `s`.`datatime` BETWEEN {$time[0]} AND {$time[1]} ");
		}
          	$roleTempId = Db::table('cfg_user')->where('id', $request->sessInfo['id'])->value('role');
		if($roleTempId) {
			$authaccount = Db::table('cfg_role')->where('companyId', $request->sessInfo['companyId'])->where('id', $roleTempId)->value('semauthaccount');
			if($authaccount) {
				array_push( $where, ['c.userId', 'in',  $authaccount ] );
			}
		}
		$query = Db::table('cfg_creative')
		->alias('c')
		->field('c.id, c.bazaarId, c.status, c.userId, c.customerid, c.contact, 
		  c.creativeId, c.title, c.adgroupName, c.adgroupId, c.campaignName, c.campaignId, c.datatime,
		  sum(s.impression) as impression,
			sum(s.clicks) as clicks,
			sum(s.cost) as cost,
			sum(s.cash) as cash,
			avg(s.rebate) as rebate,
			sum(s.copynumber) as copynumber,
			ROUND( sum(`cost`) / sum(`clicks`), 2) as `cpc`,
			ROUND( sum(`clicks`) / sum(`impression`) * 100, 2) as `ctr`,
			IF(ROUND( sum(`cost`) / sum(`copynumber`), 2 ), ROUND( sum(`cost`) / sum(`copynumber`), 2 ), sum(`cost`)) as `copycost`')
		->leftJoin('cfg_search s', 'c.creativeId = s.creativeid AND ' . implode(' AND ', $search))
		->where($where)
		->group('c.creativeId')
		->order($sort, $order)
		->paginate($limit);

		$total = Db::table('cfg_creative')
		->alias('c')
		->field('sum(s.impression) as impression,
			sum(s.clicks) as clicks,
			sum(s.cost) as cost,
			sum(s.cash) as cash,
			avg(s.rebate) as rebate,
			sum(s.copynumber) as copynumber,
			ROUND( sum(`cost`) / sum(`clicks`), 2) as `cpc`,
			ROUND( sum(`clicks`) / sum(`impression`) * 100, 2) as `ctr`,
			IF(ROUND( sum(`cost`) / sum(`copynumber`), 2 ), ROUND( sum(`cost`) / sum(`copynumber`), 2 ), sum(`cost`)) as `copycost`')
		->leftJoin('cfg_search s', 'c.creativeId = s.creativeid AND ' . implode(' AND ', $search))
		->where($where)
		->find();

		$total['impression'] = $total['impression'] ? $total['impression'] : 0;
		$total['clicks'] = $total['clicks'] ? $total['clicks'] : 0;
		$total['cost'] = $total['cost'] ? $total['cost'] : 0;
		$total['cash'] = $total['cash'] ? $total['cash'] : 0;
		$total['rebate'] = $total['rebate'] ? $total['rebate'] : 0;
		$total['cpc'] = $total['cpc'] ? $total['cpc'] : 0;
		$total['ctr'] = $total['ctr'] ? $total['ctr'] : 0;
		$total['copynumber'] = $total['copynumber'] ? $total['copynumber'] : 0;
		$total['copycost'] = $total['copycost'] ? $total['copycost'] : 0;

    $count = $query->total();
		$items = $query->items();
		foreach($items as &$value ) {
			$value['impression'] = $value['impression'] ? $value['impression'] : 0;
			$value['clicks'] = $value['clicks'] ? $value['clicks'] : 0;
			$value['cost'] = $value['cost'] ? $value['cost'] : 0;
			$value['cash'] = $value['cash'] ? $value['cash'] : 0;
			$value['rebate'] = $value['rebate'] ? $value['rebate'] : 0;
			$value['cpc'] = $value['cpc'] ? $value['cpc'] : 0;
			$value['ctr'] = $value['ctr'] ? $value['ctr'] : 0;
			$value['copynumber'] = $value['copynumber'] ? $value['copynumber'] : 0;
			$value['copycost'] = $value['copycost'] ? $value['copycost'] : 0;
		}

		return ['code'=> 0, 'msg'=> '', 'count'=> $count, 'data'=> $items, 'total' => $total,
			'expand' => Expand::getList($request->sessInfo, 1),
		  'customer' => Customer::getList($request->sessInfo),
		  'principal' => Principal::getList($request->sessInfo),
			'bazaar' => Bazaar::getList($request->sessInfo, 1)];
	}

	/**
	* 查询账号创意
	*
	* @param tValue
	* @return
	*/
	public function getCampaign(Request $request) {
		$userid = $request->param('userid', '', 'trim');
		if( empty($userid)) {
			return ['code'=> 0, 'campaign'=> [] ];
		}
		return ['code'=> 0, 'campaign'=> Campaign::getList($request->sessInfo, $userid)];
	}

	/**
	* 同步百度官方创意
	*
	* @param tValue
	* @return
	*/
	public function getCloud(Request $request) {
		if($this->hasPermission($request->sessInfo, 'semcreative:cloud')) {
			return ['code'=> 403, 'msg'=> '你没有权限执行此操作!'];;
		}

		$userId = $request->param('userId', '', 'trim');
		if( empty($userId) ) {
			return ['code'=> 403, 'msg'=> '请选择要同步的账号!'];
		}

		$obj = Expand::getUserInfo($request->sessInfo, $userId, 1);
		if(!is_object($obj)) {
			return ['code'=> 403, 'msg'=> '数据异常,请稍后重试!'];
		}

    $adgroupIds = [];
    $adgroupArray = Db::table('cfg_adgroup')->field('id, bazaarId, adgroupId, adgroupName, campaignId, campaignName')->where('userId', $obj->userid)->select()->toArray();
		if(is_array($adgroupArray)) {
			foreach( $adgroupArray as $value) {
			  array_push($adgroupIds, $value['adgroupId']);
			}
		}

		if( count($adgroupIds) == 0 ) {
			return json(['code'=> 0, 'msg'=> '操作成功!', 'data'=>[]]);
		}

    $datatime = date('Y-m-d H:i:s');
		$adgroupChunk = array_chunk($adgroupIds, 1000);
		foreach( $adgroupChunk as $ids) {
			$result = $this->getCreative($obj, $ids);
			if(isset($result['data'])) {
				foreach($result['data'] as $row) {
					$_array = cloud_get_array($adgroupArray, $row['adgroupId'], 'adgroupId');
					if( $_array !== false ) {
						$sqlArray = [];
						$row['title'] = str_replace(',', '', $row['title']);
						$id = Db::table('cfg_creative')->where('companyId', $request->sessInfo['companyId'])
							->where('creativeId', $row['creativeId'])->value('id');
						if($id) {
							Db::name('cfg_creative')->where('id', $id)->update(['status' => $row['status'], 'customerid' => $obj->customerid, 'contact' => $obj->contact, 'datatime' => $datatime]);
						} else {
							array_push($sqlArray, "( '{$request->sessInfo['companyId']}', 1, '{$obj->userid}', '{$obj->customerid}', '{$obj->contact}', '{$_array['bazaarId']}', '{$_array['adgroupName']}', '{$_array['campaignId']}', '{$_array['campaignName']}',
							  '{$row['creativeId']}', '{$row['adgroupId']}', '{$row['title']}', '{$row['status']}', NOW() ) ");
						}
						$sqlArrayIds = array_chunk($sqlArray, 3000);
						foreach( $sqlArrayIds as $sqlstr) {
							Db::execute( 'INSERT INTO cfg_creative ( `companyId`, `userType`, `userId`, `customerid`, `contact`, `bazaarId`, `adgroupName`, `campaignId`, `campaignName`, `creativeId`, `adgroupId`, `title`, `status`, `datatime` ) values ' . implode(',', $sqlstr) );
						}
					}
				}
			}
		}
		return json(['code'=> 0, 'msg'=> '操作成功!', 'data'=>[]]);
	}

	/**
	 * 设置创意状态
	 *
	 * @return
	 */
	public function setPause(Request $request)
	{
		if($this->hasPermission($request->sessInfo, 'semcreative:pause')) {
			return ['code'=> 403, 'msg'=> '你没有权限执行此操作!'];;
		}

		$beginTime = microtime(true);

		$selectId = $request->param('selectId/a', '', 'trim');
		if( count($selectId) == 0 ) {
			return ['code'=> 403, 'msg'=> '请选择要设置的创意!'];
		}

		$setCreativeArray = [];
		$getCreativeArray = [];
		$pause = $request->param('pause/d', '', 'trim');
		$queryCreative = Db::table('cfg_creative')->field('id, userId, creativeId')->where('companyId', $request->sessInfo['companyId'])
		  ->where('id', 'in', $selectId)->select()->toArray();
		if( is_array($queryCreative)) {
			foreach($queryCreative as $value) {
				$obj = Expand::getUserInfo($request->sessInfo, $value['userId'], 1);
				if(is_object($obj)) {
					if($this->isCreativeTypes($setCreativeArray, $obj->username)) {
						array_push($setCreativeArray, [
						  'userId' => $value['userId'],
							'header' => [ 'username'=> $obj->username, 'password'=> $obj->password, 'token'=> $obj->token ],
							'body' => [
								'creativeTypes'=> []
							]
						]);
					}
					if($this->isCreativeTypes($getCreativeArray, $obj->username)) {
						array_push($getCreativeArray, [
						  'userId' => $value['userId'],
							'header' => [ 'username'=> $obj->username, 'password'=> $obj->password, 'token'=> $obj->token ],
							'body' => [
									"creativeFields"=> [
										"creativeId",
										"status",
									],
									"idType"=> 7,
									"ids"=> [],
									"getTemp"=> 0
							]
						]);
					}
				}
			}
			foreach($queryCreative as $value) {
				$setIndex = array_search($value['userId'], array_column($setCreativeArray, 'userId'));
				if( $setIndex !== false ) {
				  array_push($setCreativeArray[$setIndex]['body']['creativeTypes'], [
						"creativeId"=> $value['creativeId'],
						"pause"=> $pause,
					]);
				}
				$getIndex = array_search($value['userId'], array_column($getCreativeArray, 'userId'));
				if( $getIndex !== false ) {
				  array_push($getCreativeArray[$getIndex]['body']['ids'], $value['creativeId']);
				}
			}

			foreach($setCreativeArray as $value) {
				unset($value['userId']);
				$this->updateCreative(json_encode($value));
			}

			foreach($getCreativeArray as $value) {
				unset($value['userId']);
				$response = doPostRequest('https://api.baidu.com/json/sms/service/CreativeService/getCreative', json_encode($value));
				if($response) {
					$result = json_decode ($response, true);
					if(isset($result['body']['data'])) {
						foreach($result['body']['data'] as $row) {
							Db::name('cfg_creative')->where('creativeId', $row['creativeId'])->update([
								'status' => $row['status'],
								'datatime' => date('Y-m-d H:i:s'),
							]);
						}
					}
				}
			}
		}
		$endTime = microtime(true);
		$this->cfg_write_oper($request, $request->sessInfo['token'], $request->sessInfo['companyId'], $request->sessInfo['nickname'],
		$request->sessInfo['username'], round($endTime - $beginTime, 3), '百度创意报告', '设置创意状态, ' . $pause, 0, implode(',', $selectId));
		return json(['code'=> 0, 'msg'=> '操作成功!', 'data'=>[]]);
	}

	private function isCreativeTypes($array, $username) {
		foreach($array as $value) {
			if($value['header']['username'] == $username ) {
				return false;
			}
		}
		return true;
	}

	/**
	* 创意执行地址
	*
	* @param tValue
	* @return
	*/
	private function updateCreative($parameter) {
		$request = doPostRequest('https://api.baidu.com/json/sms/service/CreativeService/updateCreative', $parameter);
		if(empty($request)) {
			return ['header'=>['desc'=>'failure', 'failures'=> [[ 'code' => 0, 'message' => 'network anomaly detection.' ]]]] ;
		}
		$result = json_decode ($request, true);
		if(!isset($result['header']['desc'])){
			return ['header'=>['desc'=>'failure', 'failures'=> [[ 'code' => 0, 'message' => 'network anomaly detection.' ]]]] ;
		}
		if(!isset($result['header']['desc'])) {
			return ['header'=>['desc'=>'failure', 'failures'=> [[ 'code' => 0, 'message' => 'network anomaly detection.' ]]]] ;
		}
		return $result;
	}

	/**
	* 读取最新创意数据
	*
	* @param tValue
	* @return
	*/
	private function getCreative($obj, $adgroupId) {
		$response = doPostRequest('https://api.baidu.com/json/sms/service/CreativeService/getCreative', json_encode([
			'header'=>['username'=> $obj->username, 'password'=> $obj->password, 'token'=>$obj->token],
			'body'=> [
        "creativeFields"=> [
            "creativeId",
            "adgroupId",
            "title",
            "status"
        ],
        "idType"=> 5,
        "ids"=> $adgroupId,
        "getTemp"=> 0
			]
		]));

		if(empty($response)) {
			return ['code'=> 403, 'msg'=> 'network anomaly detection.!'];
		}

		$result = json_decode ($response, true);
		if(!isset($result['header']['desc'])){
			return ['code'=> 403, 'msg'=> 'network anomaly detection.!'];
		}

		if(!isset($result['header']['desc'])) {
			return ['code'=> 403, 'msg'=> 'network anomaly detection.!'];
		}

		if($result['header']['desc'] == 'failure') {
			$tempMessage  = explode('sn:', $result['header']['failures'][0]['message']);
			return ['code'=> 403, 'msg'=> 'code: ' . $result['header']['failures'][0]['code'] . ' message: ' . $tempMessage[0] ];
		}

		if( isset($result['body']['data'])) {
			return ['code'=> 0, 'data'=> $result['body']['data'] ];
		}

		return ['code'=> 403, 'msg'=> 'network anomaly detection.!'];
	}

}
